//
//  ZYCTeachingAttendanceCourseDetaiViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/30.
//

#import "ZYCTeachingAttendanceCourseDetaiViewController.h"
#import "ZYCTeachingAttendanceDetailCell.h"
#import "ZYCTeachingAttendanceDetailModel.h"
#import "ZYCTeachingAttendanceDetailHeaderView.h"
#import "ZYCTeachingAttendanceDetailSectionHeaderView.h"
#import "ZYCTeachingAttendanceDetailBottomView.h"
#import "SESSFileLookController.h"
#import "ZYCTipView.h"

#define kCachePath  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]

@interface ZYCTeachingAttendanceCourseDetaiViewController ()<UITableViewDataSource,UITableViewDelegate,ZYCTeachingAttendanceDetailCellDelegate,UIDocumentInteractionControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) ZYCTeachingAttendanceDetailModel *detailModel;
@property (nonatomic, strong) ZYCTeachingAttendanceDetailHeaderView *headerView;
@property (nonatomic, strong) ZYCTeachingAttendanceDetailBottomView *footerView;

@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, strong) NSMutableArray *dataList1;
@property (nonatomic, strong) NSMutableArray *dataList2;

@property (nonatomic, strong) ZYCTipView *tipView;
@end

@implementation ZYCTeachingAttendanceCourseDetaiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
//    [self.footerView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.equalTo(self.tableView);
//        make.width.mas_equalTo(kScreenWidth);
//    }];
//    [self.tableView layoutIfNeeded];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadAttendanceCourseDetail];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.dataList.count;
    }else if(section == 1){
        return self.dataList1.count;
    }else if(section == 2){
        return self.dataList2.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCTeachingAttendanceDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeachingAttendanceDetailCell class]) forIndexPath:indexPath];
    cell.delegate = self;
    if (indexPath.section == 0) {
        cell.model = self.dataList[indexPath.row];
    }else if (indexPath.section == 1) {
        cell.model = self.dataList1[indexPath.row];
    }else if (indexPath.section == 2) {
        cell.model = self.dataList2[indexPath.row];
    }
    return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 64.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.5f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [UIView new];
    footerView.backgroundColor = HEX_RGB(@"#F9F9F9");
    return footerView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ZYCTeachingAttendanceDetailSectionHeaderView *headerView = [ZYCTeachingAttendanceDetailSectionHeaderView new];
    headerView.titleString = self.dataSource[section];
    return headerView;
}



#pragma mark - ZYCTeachingAttendanceDetailCellDelegate
- (void)teachingAttendanceDetailDidDownloadModel:(ZYCListenClassFilesModel *)model{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [kCachePath stringByAppendingPathComponent:model.fileName];
    if ([fileManager fileExistsAtPath:filePath]) {
        self.tipView.filePath = filePath;
        [self.tipView show];
    }else{
        [self download:model];
    }
}

- (void)download:(ZYCListenClassFilesModel *)model{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],model.filePath];
    
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSURLSessionDownloadTask *task = [[URLManager sharedURLManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        [MrjSVProgressHUD showWithStatus:@"下载中"];
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *cachesPath = [kCachePath stringByAppendingPathComponent:model.fileName];
        return [NSURL fileURLWithPath:cachesPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            [MrjSVProgressHUD showSuccessWithStatus:@"下载成功"];
            [self openAnnex:filePath];
        }else{
            NSLog(@"下载失败:%@",error);
        }
    }];
    [task resume];
}



#pragma mark - 网络请求


- (void)loadAttendanceCourseDetail{
    NSDictionary *params = @{
        @"listenClassId":self.listenClassId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeachAttendanceDetail requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                // 清空
                [self.dataList removeAllObjects];
                [self.dataList1 removeAllObjects];
                [self.dataList2 removeAllObjects];
                self.detailModel = [ZYCTeachingAttendanceDetailModel yy_modelWithDictionary:responseObject[@"body"]];
                //类型（1：授课教案；2：授课课件；3：其他课件；4：反思课件）
                self.headerView.model = self.detailModel;
                // 重新设置
                self.footerView.titleString = self.detailModel.instruction;
                [self.tableView layoutIfNeeded];
                self.tableView.tableFooterView = self.footerView;
                for (ZYCListenClassFilesModel *model in self.detailModel.listenClassFiles) {
                    if ([model.fileType integerValue] == 1) {
                        [self.dataList addObject:model];
                    }else if([model.fileType integerValue] == 2){
                        [self.dataList1 addObject:model];
                    }else if([model.fileType integerValue] == 3){
                        [self.dataList2 addObject:model];
                    }
                }
                [self.tableView reloadData];
           
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)openAnnex:(NSURL *)filePath{
    if ([[filePath pathExtension] isEqualToString:@"xls"]) {
        UIDocumentInteractionController *documentController = [UIDocumentInteractionController
                                   interactionControllerWithURL:filePath];
        [documentController setDelegate:self];
        [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    }else{
        SESSFileLookController *vc = [[SESSFileLookController alloc] initWithFilePath:filePath];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
    }
}



#pragma mark - getters

- (ZYCTipView *)tipView {
    if (!_tipView) {
        ZYCWeakSelf
        _tipView = [[ZYCTipView alloc] initWithFrame:CGRectMake(0, 0, 280.0f, 155.0f)];
        _tipView.title = @"温馨提示";
        _tipView.content = @"是否打开文件?";
        _tipView.clickComfirmBlock = ^(NSString * _Nonnull filePath) {
            [weakSelf openAnnex:[NSURL fileURLWithPath:filePath]];
        };
        [self.navigationController.view addSubview:_tipView];
    }
    return _tipView;
}
- (ZYCTeachingAttendanceDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCTeachingAttendanceDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 350.0f)];
    }
    return _headerView;
}

- (ZYCTeachingAttendanceDetailBottomView *)footerView {
    if (!_footerView) {
        _footerView = [[ZYCTeachingAttendanceDetailBottomView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 350.0f)];
    }
    return _footerView;
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCTeachingAttendanceDetailCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeachingAttendanceDetailCell class])];
    }
    return _tableView;
}


- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[@"授课教案",@"授课课件",@"其他附件"];
    }
    return _dataSource;
}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataList;
}

- (NSMutableArray *)dataList1 {
    if (!_dataList1) {
        _dataList1 = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataList1;
}

- (NSMutableArray *)dataList2 {
    if (!_dataList2) {
        _dataList2 = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataList2;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
